<?php
/**
* swmenumaker v1.5
* http://swmenupro.com
* Copyright 2007 Sean White
**/

// ensure this file is being included by a parent file
//error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
defined( '_JEXEC' ) or die( 'Restricted access' );

// Make sure the user is authorized to view this page
$user = & JFactory::getUser();
if (!$user->authorize( 'com_modules', 'manage' )) {
	$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') );
}
jimport( 'joomla.application.component.controller' );
$absolute_path=JPATH_ROOT;
if (file_exists(JPATH_COMPONENT.DS.'language/default.ini'))
{
$filename = JPATH_COMPONENT.DS.'language/default.ini';
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
	include(JPATH_COMPONENT.DS.'language/'.$contents);
}
//echo $mainframe->getSiteURL();
require_once( JPATH_COMPONENT.DS.'admin.swmenumaker.html.php' ) ;

$cid = JRequest::getVar( 'cid', array(0), 'post' );
if (!is_array( $cid )) {
	$cid = array(0);
}
        switch ($task) 
        {
        case "menuEdit":
        makeMenu($cid[0], $option);
        break;
        
        case "showmenus":
        showMenus( $option);       
        break; 
        
        case "removemenu":
        deleteMenu( $cid[0], $option );
        break;

        case "savemenu":
        saveMenu($cid[0], $option);
        break;

        default:
        showMenus( $option );
        break;

}

function showMenus( $option )
{
    global  $my, $mainframe;
$database = &JFactory::getDBO();
    $limit =  intval( JRequest::getVar( 'limit', 10 ) );
    $limitstart = intval( JRequest::getVar( 'limitstart', 0 ) );
    $tabid=0;
    $usetables[]= JHTML::_('select.option', '1',_SWMAK_SEC_TABLES );
	$usetables[]= JHTML::_('select.option', '0',_SWMAK_SEC_BLOGS );

$lists['usetables']= JHTML::_('select.genericlist', $usetables, 'usetables','id="usetables" class="inputbox" style="width:250px" ','value', 'text' );
 
	$query = 'SELECT DISTINCT #__menu.menutype FROM #__menu';
		$database->setQuery( $query );
		$menuTypes = $database->loadResultArray();
	$total		= count( $menuTypes );
	$i			= 0;
	
	jimport('joomla.html.pagination');
	$pageNav = new JPagination( $total, $limitstart, $limit );
        
	foreach ( $menuTypes as $a ) {
		$menus[$i]->type 		= $a;

		// query to get number of modules for menutype
		$query = "SELECT count( id )"
		. "\n FROM #__modules"
		. "\n WHERE (module = 'mod_mainmenu')"
		. "\n AND params LIKE '%menutype=$a%'"
		;
		$database->setQuery( $query );
		$modules = $database->loadResult();

		if ( !$modules ) {
			$modules = '-';
		}
		$menus[$i]->modules = $modules;

		$i++;
	}

	// Query to get published menu item counts
	$query = "SELECT a.menutype, count( a.menutype ) as num"
	. "\n FROM #__menu AS a"
	. "\n WHERE a.published = 1"
	. "\n GROUP BY a.menutype"
	. "\n ORDER BY a.menutype"
	;
	$database->setQuery( $query );
	$published = $database->loadObjectList();

	// Query to get unpublished menu item counts
	$query = "SELECT a.menutype, count( a.menutype ) as num"
	. "\n FROM #__menu AS a"
	. "\n WHERE a.published = 0"
	. "\n GROUP BY a.menutype"
	. "\n ORDER BY a.menutype"
	;
	$database->setQuery( $query );
	$unpublished = $database->loadObjectList();

	// Query to get trash menu item counts
	$query = "SELECT a.menutype, count( a.menutype ) as num"
	. "\n FROM #__menu AS a"
	. "\n WHERE a.published = -2"
	. "\n GROUP BY a.menutype"
	. "\n ORDER BY a.menutype"
	;
	$database->setQuery( $query );
	$trash = $database->loadObjectList();

	for( $i = 0; $i < $total; $i++ ) {
		// adds published count
		foreach ( $published as $count ) {
			if ( $menus[$i]->type == $count->menutype ) {
				$menus[$i]->published = $count->num;
			}
		}
		if ( @!$menus[$i]->published ) {
			$menus[$i]->published = '-';
		}
		// adds unpublished count
		foreach ( $unpublished as $count ) {
			if ( $menus[$i]->type == $count->menutype ) {
				$menus[$i]->unpublished = $count->num;
			}
		}
		if ( @!$menus[$i]->unpublished ) {
			$menus[$i]->unpublished = '-';
		}
		// adds trash count
		foreach ( $trash as $count ) {
			if ( $menus[$i]->type == $count->menutype ) {
				$menus[$i]->trash = $count->num;
			}
		}
		if ( @!$menus[$i]->trash ) {
			$menus[$i]->trash = '-';
		}
	}
	$sql =  "SELECT DISTINCT #__sections.id AS value, #__sections.title AS text
             FROM #__sections                                    
             INNER JOIN #__content ON #__content.sectionid = #__sections.id
             AND #__sections.published = 1
            ";

        $database->setQuery( $sql );
        $sections = $database->loadObjectList();
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_SEC );
       // $categories3[]= JHTML::_('select.option', -999, '--------' );
        foreach($sections as $sections2){
            $categories3[]= JHTML::_('select.option', ('sec'.$sections2->value), '-- '.$sections2->text );
        }
       // $categories3[]= JHTML::_('select.option', -999, '&nbsp;' );
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_CAT );
      //  $categories3[]= JHTML::_('select.option', -999, '----------' );
        
       $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text,#__sections.title AS section
                FROM #__categories , #__sections                                 
                WHERE #__sections.id=#__categories.section
                AND #__categories.published = 1
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ('cat'.$categories2->value), '-- '.$categories2->section." / ".$categories2->text );
        }
        
       // $categories3[]= JHTML::_('select.option', -999, '&nbsp;' );
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_STATIC );
       // $categories3[]= JHTML::_('select.option', -999, '----------' );
        
         $sql =  "SELECT DISTINCT #__content.id AS value, #__content.title AS text
                FROM #__content                                  
                WHERE #__content.sectionid=0
                AND #__content.catid =0
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ('sta'.$categories2->value), '-- '.$categories2->text );
        }
        
       // $categories3[]= JHTML::_('select.option', -999, '&nbsp;' );
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_NEWSFEED );
      //  $categories3[]= JHTML::_('select.option', -999, '----------' );
        
        
        $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text
                FROM #__categories                                  
                INNER JOIN #__newsfeeds ON #__newsfeeds.catid = #__categories.id
                AND #__categories.published = 1
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ('new'.$categories2->value), '-- '.$categories2->text );
        }
        
       // $categories3[]= JHTML::_('select.option', -999, '&nbsp;' );
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_CONTACTS );
       // $categories3[]= JHTML::_('select.option', -999, '----------' );
        
        
        $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text
                FROM #__categories                                  
                INNER JOIN #__contact_details ON #__contact_details.catid = #__categories.id
                AND #__categories.published = 1
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ('con'.$categories2->value), '-- '.$categories2->text );
        }
        
       // $categories3[]= JHTML::_('select.option', -999, '&nbsp;' );
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_WEBLINKS);
       // $categories3[]= JHTML::_('select.option', -999, '----------' );
        
          $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text
                FROM #__categories                                  
                INNER JOIN #__weblinks ON #__weblinks.catid = #__categories.id
                AND #__categories.published = 1
                ";
       
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ('web'.$categories2->value), '-- '.$categories2->text );
        }
        
       // $categories3[]= JHTML::_('select.option', -999, '&nbsp;' );
        $categories3[]= JHTML::_('select.option', "<OPTGROUP>", _SWMAK_COMPONENTS );
     //   $categories3[]= JHTML::_('select.option', -999, '----------' );
        
        $sql =  "SELECT DISTINCT #__components.id AS value, #__components.name AS text
                FROM #__components                                  
                WHERE #__components.parent=0
                AND #__components.link != ''
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ('com'.$categories2->value), '-- '.$categories2->text );
        }
        
$lists['category']= JHTML::_('select.genericlist', $categories3, 'category[]',' multiple="multiple" class="inputbox" size="18" style="width:250px" ','value', 'text');

$menus = array_slice( $menus, $pageNav->limitstart, $pageNav->limit );
	
HTML_swmenumaker::showMenus( $rows, $option, $pageNav,$lists,$menus,$tabid );
HTML_swmenumaker::footer( );
}


function deleteMenu( $id,$option ) {
	global $mainframe;
	$database = &JFactory::getDBO();
	$type=JRequest::getVar('menuname',"");
	
	if ( $type == 'mainmenu' ) {
		echo "<script> alert('You cannot delete the \'mainmenu\' menu as it is core menu'); window.history.go(-1); </script>\n";
		exit();
	}

	$query = "DELETE FROM #__menu"
	. "\n WHERE ( menutype='$type' )"
	;
	$database->setQuery( $query );
	if ( !$database->query() ) {
		echo "<script> alert('". $database->getErrorMsg() ."');</script>\n";
		exit;
	}
$query = "DELETE FROM #__menu_types"
	. "\n WHERE ( menutype='$type' )"
	;
	$database->setQuery( $query );
	if ( !$database->query() ) {
		echo "<script> alert('". $database->getErrorMsg() ."');</script>\n";
		exit;
	}
  $query = "SELECT id"
			. "\n FROM #__modules"
			. "\n WHERE (module = 'mod_mainmenu')"
			. "\n AND params LIKE '%menutype=$type%'"
			;
			$database->setQuery( $query );
			$cid = $database->loadResultArray();

			if ( is_array( $cid ) ) {
		$cids = implode( ',', $cid );
	} else {
		$cids = $cid;
	}

	// checks whether any modules to delete
	if ( $cids ) {
		
		// delete modules
		$query = "DELETE FROM #__modules"
		. "\n WHERE id IN ( $cids )"
		;
		$database->setQuery( $query );
		if ( !$database->query() ) {
			echo "<script> alert('". $database->getErrorMsg() ."'); window.history.go(-1); </script>\n";
			exit;
		}
		// delete all module entires in jos_modules_menu
		$query = "DELETE FROM #__modules_menu"
		. "\n WHERE moduleid IN ( $cids )"
		;
		$database->setQuery( $query );
		if ( !$database->query() ) {
			echo "<script> alert('". $database->getErrorMsg() ."');</script>\n";
			exit;
		}
	}
// reorder modules after deletion
	$msg="Menu sucessfully deleted";
    $limit = intval( JRequest::getVar( 'limit', 10 ) );
    $limitstart = intval( JRequest::getVar( 'limitstart', 0 ) );
   $mainframe->redirect( "index2.php?task=showmenus&option=$option&limit=$limit&limitstart=$limitstart",$msg );
	
}


function makeMenu( $id, $option )
{

global $mosConfig_lang, $mosConfig_mbf_content, $mosConfig_offset;
$database = &JFactory::getDBO();
$my = & JFactory::getUser();
 $swmenumaker_array=array();
 $now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );
 $copymenu=( JRequest::getVar( 'copymenu', 0 ) );	
 $menu=( JRequest::getVar( 'menuname', "" ) );
 $menuid=( JRequest::getVar( 'menu_id', '' ) );
 $use_tables=( JRequest::getVar( 'usetables', 0 ) );
 $new=( JRequest::getVar( 'newmenu2', '' ) );
 $limit=intval( JRequest::getVar( 'limit', 10 ) );
 $limitstart=intval( JRequest::getVar( 'limitstart', 0 ) );

	if($new){
		
	$menusource= JRequest::getVar( 'category', array()  );	
	
	foreach ($menusource as $source) {
	 if(substr($source,0,3)=="sec"){
		//echo "hello".substr($source,3);
		$secid=substr($source,3);
		
		$sql =  "SELECT #__sections.*
				FROM #__sections
                INNER JOIN #__content ON #__content.sectionid = #__sections.id
                AND #__sections.id = ".$secid."
                AND #__content.access <= ".$my->gid."
                ORDER BY #__content.ordering
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
                if($use_tables){
                $url="index.php?option=com_content&view=section&id=" . $result2->id ;
                 $ltype="content_section";
                }else{
                  $url="index.php?option=com_content&view=section&layout=blog&id=" . $result2->id ;
                   $ltype="content_blog_section";
                }

                $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+100000  , 
                "PARENT" => 0 ,  "ORDER" => $result2->ordering, "PUBLISHED"=>$result2->published, "TARGET" => 0,"LINKTYPE"=>$ltype );
            }
		
		$sql =  "SELECT #__categories.* 
            	FROM #__categories
                INNER JOIN #__content ON #__content.catid = #__categories.id
                AND #__categories.section = ".$secid."
                AND #__content.access <= ".$my->gid."
                ORDER BY #__content.ordering
                ";

            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {

                if($use_tables){
                $url="index.php?option=com_content&view=category&id=" . $result2->id ;
                $ltype="content_category";
                }else{
                  $url="index.php?option=com_content&view=category&layout=blog&id=" . $result2->id ;
                  $ltype="content_blog_category";
                }

                $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+1000000  , 
                "PARENT" => $result2->section+100000 , "LINKTYPE"=> $ltype,
                 "ORDER" => $result2->ordering, "PUBLISHED"=>$result2->published, "TARGET" => 0 );
            }

            $sql =  "SELECT #__content.* 
                FROM #__content
                INNER JOIN #__categories ON #__content.catid = #__categories.id
                AND #__content.access <= ".$my->gid."
                ORDER BY #__content.ordering
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
            $url="index.php?option=com_content&view=article&id=" . $result2->id ;


            $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => $result2->catid+1000000 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>$result2->state, "LINKTYPE"=> "content_item_link");

        }
	}else if(substr($source,0,3)=="cat"){
	
	$catid=substr($source,3);
	
	$sql =  "SELECT #__categories.* 
            	FROM #__categories
                INNER JOIN #__content ON #__content.catid = #__categories.id
                AND #__categories.id = ".$catid."
                AND #__content.access <= ".$my->gid."
                ORDER BY #__content.ordering
                ";

            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {

             if($use_tables){
                $url="index.php?option=com_content&view=category&id=" . $result2->id ;
                $ltype="content_category";
                }else{
                  $url="index.php?option=com_content&view=category&layout=blog&id=" . $result2->id ;
                  $ltype="content_blog_category";
                }

                $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+1000000  , 
                "PARENT" => 0 , "LINKTYPE"=> $ltype,
                 "ORDER" => $result2->ordering, "PUBLISHED"=>$result2->published, "TARGET" => 0 );
            }
	
	$sql =  "SELECT #__content.* 
                FROM #__content
                INNER JOIN #__categories ON #__content.catid = #__categories.id
                AND #__content.catid = ".$catid."
                AND #__content.access <= ".$my->gid."
                ORDER BY #__content.ordering
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();


            foreach ($result as $result2) {
            $url="index.php?option=com_content&view=article&id=" . $result2->id ;

            $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => $result2->catid+1000000 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>$result2->state, "LINKTYPE"=> "content_item_link");
        }
	}else if(substr($source,0,3)=="new"){
	
	$catid=substr($source,3);
	
	$sql =  "SELECT #__categories.* 
            	FROM #__categories
                INNER JOIN #__newsfeeds ON #__newsfeeds.catid = #__categories.id
                AND #__categories.id = ".$catid."
               
                ";

            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
                $url="index.php?option=com_newsfeeds&view=category&id=" . $result2->id ;
                $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+1000000  , 
                "PARENT" => 0 , "LINKTYPE"=> "newsfeed_category_table",
                 "ORDER" => $result2->ordering, "PUBLISHED"=>$result2->published, "TARGET" => 0 );
            }
	
	$sql =  "SELECT #__newsfeeds.* 
                FROM #__newsfeeds
                INNER JOIN #__categories ON #__newsfeeds.catid = #__categories.id
               
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
            $url="index.php?option=com_newsfeeds&view=newsfeed&id=" . $result2->id ;

            $swmenumaker_array[] =array("NAME" => $result2->name, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => $result2->catid+1000000 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>$result2->published, "LINKTYPE"=> "newsfeed_link");

        }
	}else if(substr($source,0,3)=="con"){
	
	$catid=substr($source,3);
	
	$sql =  "SELECT #__categories.* 
            	FROM #__categories
                INNER JOIN #__contact_details ON #__contact_details.catid = #__categories.id
                AND #__categories.id = ".$catid."
               
                ";

            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
                $url="index.php?option=com_contact&view=category&catid=".$result2->id ;
                
                $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+1000000  , 
                "PARENT" => 0 , "LINKTYPE"=> "contact_category_table",
                 "ORDER" => $result2->ordering, "PUBLISHED"=>$result2->published, "TARGET" => 0 );
            }
	
	$sql =  "SELECT #__contact_details.* 
                FROM #__contact_details
                INNER JOIN #__categories ON #__contact_details.catid = #__categories.id
               
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();


            foreach ($result as $result2) {
            $url="index.php?option=com_contact&view=contact&id=" . $result2->id ;
            $swmenumaker_array[] =array("NAME" => $result2->name, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => $result2->catid+1000000 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>$result2->published, "LINKTYPE"=> "contact_item_link");

        }
	
	}else if(substr($source,0,3)=="web"){
	
	$catid=substr($source,3);
	
	$sql =  "SELECT #__categories.* 
            	FROM #__categories
                INNER JOIN #__weblinks ON #__weblinks.catid = #__categories.id
                AND #__categories.id = ".$catid."
               
                ";

            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
                $url="index.php?option=com_weblinks&view=category&id=" . $result2->id ;
                $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+1000000  , 
                "PARENT" => 0 , "LINKTYPE"=> "weblink_category_table",
                 "ORDER" => $result2->ordering, "PUBLISHED"=>$result2->published, "TARGET" => 0 );
            }
	
	$sql =  "SELECT #__weblinks.* 
                FROM #__weblinks
                INNER JOIN #__categories ON #__weblinks.catid = #__categories.id
               
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();


            foreach ($result as $result2) {
            $url="index.php?option=com_weblinks&view=weblink&id=".$result2->id ;
            $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => $result2->catid+1000000 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>$result2->published, "LINKTYPE"=> "weblink_link");

        }
	}else if(substr($source,0,3)=="sta"){
	
	$catid=substr($source,3);
	$sql =  "SELECT #__content.* 
                FROM #__content
                WHERE #__content.id = ".$catid."
               
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();

            foreach ($result as $result2) {
            $url="index.php?option=com_content&view=article&id=" . $result2->id ;
            $swmenumaker_array[] =array("NAME" => $result2->title, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => 0 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>$result2->state, "LINKTYPE"=> "content_typed");
        }
	}else if(substr($source,0,3)=="com"){
	
	$catid=substr($source,3);

	$sql =  "SELECT #__components.* 
                FROM #__components
                WHERE #__components.id = ".$catid."
               
                ";
            $database->setQuery( $sql   );
            $result = $database->loadObjectList();
            foreach ($result as $result2) {
            $url="index.php?". $result2->link ;

            $swmenumaker_array[] =array("NAME" => $result2->name, "URL" =>  $url , "ID" => $result2->id+10000000  , 
            "PARENT" => 0 ,  "ORDER" => $result2->ordering, 
            "TARGET" => 0,"PUBLISHED"=>1, "LINKTYPE"=> "components");
        }
	}
	
	}			
	}elseif($copymenu){
	
	$sql = "SELECT #__menu.* 
                FROM #__menu 
                WHERE #__menu.menutype = '".$menu."' 
                AND access <= '$my->gid'
                 AND published >= '0'
                ORDER BY parent, ordering
            ";
	$database->setQuery( $sql   );
	$result = $database->loadObjectList();
	
	$swmenumaker_array=array();

	foreach ($result as $result2) {
		$order=0;
		
		$opt=array();
		
		if($result2->type!="url"){
			$vars=substr($result2->link,(strpos($result2->link,"?")+1));
				parse_str($vars, $opt);
				$opt['view'] = @$opt['view'] ? $opt['view']: "";
				$opt['id'] = @$opt['id'] ? $opt['id']: 0;
				$opt['option'] = @$opt['option'] ? $opt['option']: "";
				$opt['layout'] = @$opt['layout'] ? $opt['layout']: "";
				//echo $opt['option'].$vars;
				
				if ($opt['option']=="com_content" || $opt['option']=="content" ) {
					if ($opt['view']=="blogcategory" || $opt['view']=="category" ) {
						if($opt['layout']=="blog"){
						$result2->type="content_blog_category";
						}else{
						$result2->type="content_category";	
						}
					}
					if ($opt['view']=="blogsection" || $opt['view']=="section" ) {
						if($opt['layout']=="blog"){
							$result2->type="content_blog_section";
							}else{
							$result2->type="content_section";	
							}
					}
					if ($opt['view']=="article" ) {
					if($opt['layout']=="form"){
							$result2->type="submit_content";
							}else{
							$result2->type="content_item_link";	
							}
					}
					if ($opt['view']=="archive") {
						$result2->type="content_archive_section";	
					}
					if ($opt['view']=="frontpage") {
						$result2->type="content_frontpage";	
					}
				}else if (($opt['option']=="com_contact") ||($opt['option']=="contact") ) {
					if ($opt['view']=="blogcategory" || $opt['view']=="category" ) {
						$result2->type="contact_category_table";	
					}else{
						$result2->type="contact_item_link";	
					}
				}else if ($opt['option']=="com_newsfeeds" || $opt['option']=="newsfeeds" ) {
					if ($opt['view']=="categories" ) {
						$result2->type="newsfeed_category_list";	
					}else if ($opt['view']=="category" ){
						$result2->type="newsfeed_category_table";	
					}else if ($opt['view']=="newsfeed" ){
						$result2->type="newsfeed_link";	
					}
				}else if (($opt['option']=="com_poll") ||($opt['option']=="poll") ) {
					if ($opt['view']=="poll" ) {
						$result2->type="poll_link";	
					}else{
						$result2->type="component";	
					}
				}else if ($opt['option']=="com_user" || $opt['option']=="user" ) {
					if ($opt['view']=="login" ) {
						$result2->type="user_login";	
					}else if ($opt['view']=="register" ){
						$result2->type="user_registration";	
					}else if ($opt['view']=="remind" ){
						$result2->type="user_reminder";	
					}else if ($opt['view']=="user" ){
						if($opt['layout']=="form"){
							$result2->type="user_form";
							}else{
							$result2->type="user_default";	
							}
					}else if ($opt['view']=="reset" ){
						$result2->type="user_reset";	
					}
				}else if ($opt['option']=="com_weblinks" || $opt['option']=="weblinks" ) {
					if ($opt['view']=="categories" ) {
						$result2->type="weblink_category_list";	
					}else if ($opt['view']=="category" ){
						$result2->type="weblink_category_table";	
					}else if ($opt['view']=="weblink"){
						if( $opt['layout']=="form" ){
						$result2->type="weblink_submit";
						}else{
						$result2->type="weblink_link";
						}	
					}
				}else if (($opt['option']=="com_wrapper") ||($opt['option']=="wrapper") ) {
					$result2->type="wrapper";	
				}else if (substr($opt['option'],0,4)=="com_")  {
					$result2->type="components";	
				}
				
		}
		$swmenumaker_array[] =array("TITLE" => $result2->name,
		"NAME" => $result2->name, "URL" =>  $result2->link , "ID" => $result2->id+10000000  , 
		"PARENT" => $result2->parent ? $result2->parent+10000000:0 ,  "ORDER" => $result2->ordering, "LINKTYPE" => $result2->type,
		"TYPE" => $result2->type, "ACCESS" => $result2->access, "COMPID" => $result2->componentid,
		"PUBLISHED" => $result2->published, "UTACCESS" => $result2->utaccess,
		"TARGET" => $result2->browserNav,"PARAMS" => $result2->params );
		}
	$menu="";
	}else{
		$sql = "SELECT #__menu.* 
                FROM #__menu 
                WHERE #__menu.menutype = '".$menu."' 
                AND access <= '$my->gid'
                  AND published >= '0'
                ORDER BY parent, ordering
            ";
	$database->setQuery( $sql   );
	$result = $database->loadObjectList();
	
	$swmenumaker_array=array();

	foreach ($result as $result2) {
		$order=0;
		
		$opt=array();
		
		if($result2->type!="url"){
			$vars=substr($result2->link,(strpos($result2->link,"?")+1));
				parse_str($vars, $opt);
				$opt['view'] = @$opt['view'] ? $opt['view']: "";
				$opt['id'] = @$opt['id'] ? $opt['id']: 0;
				$opt['option'] = @$opt['option'] ? $opt['option']: "";
				$opt['layout'] = @$opt['layout'] ? $opt['layout']: "";
				//echo $opt['option'].$vars;
				
				if ($opt['option']=="com_content" || $opt['option']=="content" ) {
					if ($opt['view']=="blogcategory" || $opt['view']=="category" ) {
						if($opt['layout']=="blog"){
						$result2->type="content_blog_category";
						}else{
						$result2->type="content_category";	
						}
					}
					if ($opt['view']=="blogsection" || $opt['view']=="section" ) {
						if($opt['layout']=="blog"){
							$result2->type="content_blog_section";
							}else{
							$result2->type="content_section";	
							}
					}
					if ($opt['view']=="article" ) {
					if($opt['layout']=="form"){
							$result2->type="submit_content";
							}else{
							$result2->type="content_item_link";	
							}
					}
					if ($opt['view']=="archive") {
						$result2->type="content_archive_section";	
					}
					if ($opt['view']=="frontpage") {
						$result2->type="content_frontpage";	
					}
				}else if (($opt['option']=="com_contact") ||($opt['option']=="contact") ) {
					if ($opt['view']=="blogcategory" || $opt['view']=="category" ) {
						$result2->type="contact_category_table";	
					}else{
						$result2->type="contact_item_link";	
					}
				}else if ($opt['option']=="com_newsfeeds" || $opt['option']=="newsfeeds" ) {
					if ($opt['view']=="categories" ) {
						$result2->type="newsfeed_category_list";	
					}else if ($opt['view']=="category" ){
						$result2->type="newsfeed_category_table";	
					}else if ($opt['view']=="newsfeed" ){
						$result2->type="newsfeed_link";	
					}
				}else if (($opt['option']=="com_poll") ||($opt['option']=="poll") ) {
					if ($opt['view']=="poll" ) {
						$result2->type="poll_link";	
					}else{
						$result2->type="component";	
					}
				}else if ($opt['option']=="com_user" || $opt['option']=="user" ) {
					if ($opt['view']=="login" ) {
						$result2->type="user_login";	
					}else if ($opt['view']=="register" ){
						$result2->type="user_registration";	
					}else if ($opt['view']=="remind" ){
						$result2->type="user_reminder";	
					}else if ($opt['view']=="user" ){
						if($opt['layout']=="form"){
							$result2->type="user_form";
							}else{
							$result2->type="user_default";	
							}
					}else if ($opt['view']=="reset" ){
						$result2->type="user_reset";	
					}
				}else if ($opt['option']=="com_weblinks" || $opt['option']=="weblinks" ) {
					if ($opt['view']=="categories" ) {
						$result2->type="weblink_category_list";	
					}else if ($opt['view']=="category" ){
						$result2->type="weblink_category_table";	
					}else if ($opt['view']=="weblink"){
						if( $opt['layout']=="form" ){
						$result2->type="weblink_submit";
						}else{
						$result2->type="weblink_link";
						}	
					}
				}else if (($opt['option']=="com_wrapper") ||($opt['option']=="wrapper") ) {
					$result2->type="wrapper";	
				}else if (substr($opt['option'],0,4)=="com_")  {
					$result2->type="components";	
				}
				
		}
		
		$swmenumaker_array[] =array("TITLE" => $result2->name,
		"NAME" => $result2->name, "URL" =>  $result2->link , "ID" => $result2->id  , 
		"PARENT" => $result2->parent ,  "ORDER" => $result2->ordering, "LINKTYPE" => $result2->type,
		"TYPE" => $result2->type, "ACCESS" => $result2->access, "COMPID" => $result2->componentid,
		"PUBLISHED" => $result2->published, "UTACCESS" => $result2->utaccess,
		"TARGET" => $result2->browserNav,"PARAMS" => $result2->params );
	}
	}
	// $swmenumaker_array= fixOrder2($swmenumaker_array, 0);
	if (count($swmenumaker_array)){
		$ordered = chain('ID', 'PARENT', 'ORDER', $swmenumaker_array, 0, 15);
		$i=0;
		foreach ($ordered as $row){
			
			if ((@$ordered[($i+1)]['PARENT']==$row['ID'] )){
				$ordered[$i]['TYPE']="folder";
			}else{
				$ordered[$i]['TYPE']="doc";
			}
			$i++;
		}
		
	}else{
		$ordered = array();
		$menudisplay=0;
	}
	
	$v['id']="test";
	$lists=array();
	$type[]= JHTML::_('select.option', '','Select Link Type' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Articles' );
	$type[]= JHTML::_('select.option', 'content_archive_section','Archive List' );
	$type[]= JHTML::_('select.option', 'content_item_link','Article Link' );
	$type[]= JHTML::_('select.option', 'submit_content','Article Submit' );
	$type[]= JHTML::_('select.option', 'content_blog_category','Category Blog' );
	$type[]= JHTML::_('select.option', 'content_category','Category List' );
	$type[]= JHTML::_('select.option', 'content_frontpage','Frontpage Blog' );
	$type[]= JHTML::_('select.option', 'content_blog_section','Section Blog' );
	$type[]= JHTML::_('select.option', 'content_section','Section List' );
	
	
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Contacts' );
	$type[]= JHTML::_('select.option', 'contact_category_table','Contact Category' );
	$type[]= JHTML::_('select.option', 'contact_item_link','Contact Link' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Newsfeeds' );
	$type[]= JHTML::_('select.option', 'newsfeed_category_list','Newsfeed List' );
	$type[]= JHTML::_('select.option', 'newsfeed_category_table','Newsfeed Category' );
	$type[]= JHTML::_('select.option', 'newsfeed_link','Newsfeed Link' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Polls' );
	$type[]= JHTML::_('select.option', 'poll_link','Poll Link' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Components' );
	//$type[]= JHTML::_('select.option', 'component_item_link','Component Link' );
	$type[]= JHTML::_('select.option', 'components','Component Link' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Users' );
	$type[]= JHTML::_('select.option', 'user_login','User Login' );
	$type[]= JHTML::_('select.option', 'user_registration','User Registration' );
	$type[]= JHTML::_('select.option', 'user_reminder','User Reminder' );
	$type[]= JHTML::_('select.option', 'user_reset','User Reset' );
	$type[]= JHTML::_('select.option', 'user_default','User Default' );
	$type[]= JHTML::_('select.option', 'user_form','User Form' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Weblinks' );
	$type[]= JHTML::_('select.option', 'weblink_category_table','Weblink Category' );
	$type[]= JHTML::_('select.option', 'weblink_category_list','Weblink List' );
	$type[]= JHTML::_('select.option', 'weblink_link','Weblink Link' );
	$type[]= JHTML::_('select.option', 'weblink_submit','Weblink Submit' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Separator' );
	$type[]= JHTML::_('select.option', 'separator','Separator' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','Wrapper' );
	$type[]= JHTML::_('select.option', 'wrapper','Wrapper' );
	
	$type[]= JHTML::_('select.option', '<OPTGROUP>','External Link' );
	$type[]= JHTML::_('select.option', 'url','URL Link' );
	
	
	$lists['linktype']= JHTML::_('select.genericlist', $type, 'tree-info-linktype','id="tree-info-linktype" style="width:220px" class="inputbox" onchange="changeDynaList2(\'existlink\',orders2,document.getElementById(\'tree-info-linktype\').options[document.getElementById(\'tree-info-linktype\').selectedIndex].value, originalPos2, originalOrder2,\'update\');"','value', 'text', '' );
	$lists['new_linktype']= JHTML::_('select.genericlist', $type, 'tree-insert-linktype','id="tree-insert-linktype" style="width:220px" class="inputbox" onchange="changeDynaList2(\'parentid\',orders2,document.getElementById(\'tree-insert-linktype\').options[document.getElementById(\'tree-insert-linktype\').selectedIndex].value, originalPos2, originalOrder2,\'new\');"','value', 'text', '' );

	$categories3= array();
    $sql =  "SELECT DISTINCT #__sections.id AS value, #__sections.title AS text
                FROM #__sections                                    
                INNER JOIN #__content ON #__content.sectionid = #__sections.id
                AND #__sections.published = 1
                ";

        $database->setQuery( $sql );
        $sections = $database->loadObjectList();
       
        foreach($sections as $sections2){
            $categories3[]= JHTML::_('select.option', ($sections2->value), $sections2->text );
        }
  
        
       $menuitems['content_blog_section'][] = JHTML::_('select.option', "0", "Select All Sections For Blog Display" );
	   $menuitems['content_section'][] = JHTML::_('select.option', "0", "Select Section For Table Display" );
	  // $menuitems['content_archive_section'][] = JHTML::_('select.option', "", "Select Section Archive For Blog Display" );
	   $menuitems['submit_content'][] = JHTML::_('select.option', "", "Select Section for Users to Submit Content" );
	   
foreach($categories3 as $category){
	$menuitems['content_blog_section'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
	$menuitems['content_section'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
//	$menuitems['content_archive_section'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
	$menuitems['submit_content'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );	
}     
 $categories3= array();
        
        $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text,#__sections.title AS sectionname
                FROM #__categories                                  
                INNER JOIN #__sections ON #__sections.id = #__categories.section
                AND #__categories.published = 1
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->sectionname." / ".$categories2->text );
        }
$menuitems['content_blog_category'][] = JHTML::_('select.option', "0", "Select All Categories For Blog Display"  );
$menuitems['content_category'][] = JHTML::_('select.option', "", "Select Category For Table Display"  );
$menuitems['content_archive_category'][] = JHTML::_('select.option', "","Select Category Archive For Blog Display"  );

 foreach($categories3 as $category){
$menuitems['content_blog_category'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['content_archive_category'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['content_category'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    
	
$categories3= array();
        
        $sql =  "SELECT DISTINCT #__content.id AS value, #__content.title AS text, #__categories.title AS catname, #__sections.title AS secname
                FROM #__content , #__categories, #__sections                             
                WHERE #__content.catid = #__categories.id
                AND #__sections.id = #__categories.section
                AND #__content.state = 1
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->secname." / ".$categories2->catname." / ".$categories2->text );
        }
$menuitems['content_item_link'][] = JHTML::_('select.option', "", "Select Content to Display" );

 foreach($categories3 as $category){
$menuitems['content_item_link'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['content_category'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    
$categories3= array();
        
        $sql =  "SELECT DISTINCT #__components.link AS value, #__components.name AS text
                FROM #__components                                  
                WHERE #__components.parent=0
                AND #__components.link != ''
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['components'][] = JHTML::_('select.option', "", "Select Component to Display"  );
$menuitems['component_item_link'][] = JHTML::_('select.option', "", "Select Component to Link To"  );

 foreach($categories3 as $category){
$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['component_item_link'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
}
$categories3= array();
        
        $sql =  "SELECT #__contact_details.id AS value, #__contact_details.name AS text, #__categories.title AS catname 
                FROM #__contact_details
                INNER JOIN #__categories ON #__contact_details.catid = #__categories.id        
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->catname." / ".$categories2->text );
        }
$menuitems['contact_item_link'][] = JHTML::_('select.option', "", "Select Contact to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['contact_item_link'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    

$categories3= array();
        
        $sql =  "SELECT #__categories.id AS value, #__categories.title AS text 
                FROM #__categories
                INNER JOIN #__contact_details ON #__contact_details.catid = #__categories.id
               
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['contact_category_table'][] = JHTML::_('select.option', "", "Select Contact Category to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['contact_category_table'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
}    
$categories3= array();
        
        $sql =  "SELECT #__content.id AS value, #__content.title AS text 
                FROM #__content
                WHERE #__content.catid = 0
               
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['content_typed'][] = JHTML::_('select.option', "", "Select Static Content to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['content_typed'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    
$categories3= array();
        
        $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text 
                FROM #__categories
                INNER JOIN #__newsfeeds ON #__newsfeeds.catid = #__categories.id
               
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['newsfeed_category_table'][] = JHTML::_('select.option', "", "Select Newsfeed Category to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['newsfeed_category_table'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    

$categories3= array();
        
        $sql =  "SELECT DISTINCT #__newsfeeds.id AS value, #__newsfeeds.name AS text, #__categories.title AS catname 
                FROM #__newsfeeds
                INNER JOIN #__categories ON #__newsfeeds.catid = #__categories.id
               
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->catname." / ".$categories2->text );
        }
$menuitems['newsfeed_link'][] = JHTML::_('select.option', "", "Select Newsfeed Item to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['newsfeed_link'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    

$categories3= array();
        
        $sql =  "SELECT DISTINCT #__polls.id AS value, #__polls.title AS text 
                FROM #__polls
                
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['poll_link'][] = JHTML::_('select.option', "", "Select Poll to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['poll_link'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    

$categories3= array();
        
        $sql =  "SELECT DISTINCT #__weblinks.id AS value, #__weblinks.title AS text 
                FROM #__weblinks
                
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['weblink_link'][] = JHTML::_('select.option', "", "Select a Weblink"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['weblink_link'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    
	
$categories3= array();
        
        $sql =  "SELECT DISTINCT #__categories.id AS value, #__categories.title AS text 
                FROM #__categories
                INNER JOIN #__weblinks ON #__weblinks.catid = #__categories.id
               
                ";
        $database->setQuery( $sql );
        $categories = $database->loadObjectList();
        
        foreach($categories as $categories2){
            $categories3[]= JHTML::_('select.option', ($categories2->value), $categories2->text );
        }
$menuitems['weblink_category_table'][] = JHTML::_('select.option', "", "Select Weblink Category to Display"  );

 foreach($categories3 as $category){
//$menuitems['components'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );
$menuitems['weblink_category_table'][] = JHTML::_('select.option', $category->value, addslashes($category->text) );

}    
	$access[]= JHTML::_('select.option', '0','Public' );
	$access[]= JHTML::_('select.option', '1','Registered' );
	$access[]= JHTML::_('select.option', '2','Special' );
	$lists['access']= JHTML::_('select.genericlist', $access, 'tree-info-access','id="tree-info-access" class="inputbox" ','value', 'text', '0' );
	$lists['new_access']= JHTML::_('select.genericlist', $access, 'tree-insert-access','id="tree-insert-access" class="inputbox" ','value', 'text', '0' );
	
	$target[]= JHTML::_('select.option', '0','Parent Window With Browser Navigation' );
	$target[]= JHTML::_('select.option', '1','New Window With Browser Navigation' );
	$target[]= JHTML::_('select.option', '2','New Window Without Browser Navigation' );
	$lists['target']= JHTML::_('select.genericlist', $target, 'tree-info-target','id="tree-info-target" style="width:230px;" class="inputbox" ','value', 'text', '' );
	$lists['new_target']= JHTML::_('select.genericlist', $target, 'tree-insert-target','id="tree-insert-target" style="width:230px;" class="inputbox" ','value', 'text', '' );

	
	$published[]= JHTML::_('select.option', '0','No' );
	$published[]= JHTML::_('select.option', '1','Yes' );
	$lists['published']= JHTML::_('select.genericlist', $published, 'tree-info-published','id="tree-info-published" class="inputbox" ','value', 'text', '' );
	$lists['new_published']= JHTML::_('select.genericlist', $published, 'tree-insert-published','id="tree-insert-published" class="inputbox" ','value', 'text', '1' );
	
	
	
	//$lists['published'] = JHTML::_('select.booleanlist', 'tree-info-published', 'class="inputbox" id="tree-info-published" ', 1 );
	//$lists['new_published'] = JHTML::_('select.booleanlist', 'tree-insert-published', 'class="inputbox" id="tree-insert-published" ', 1 );

	$type2[]= JHTML::_('select.option', 'folder','Folder' );
	$type2[]= JHTML::_('select.option', 'doc','Document' );
	$lists['type']= JHTML::_('select.genericlist', $type2, 'tree-info-type','id="tree-info-type" class="inputbox" onchange="docwarn();"','value', 'text', '' );
	
	//$user = new mosUser( $database );
	// load the row from the db table
	//$user->load( $my->id );
	$username=$my->username;
	HTML_swmenumaker::makeMenu( $ordered, $option, $menuid, $menu, 0, $limit, $limitstart,$lists, $username,$new,$copymenu,$menuitems );
	HTML_swmenumaker::footer( );
}





function chain($primary_field, $parent_field, $sort_field, $rows, $root_id=0, $maxlevel=25)
{
   $c = new chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel);
   return $c->chain_table;
}

class chain
{
   var $table;
   var $rows;
   var $chain_table;
   var $primary_field;
   var $parent_field;
   var $sort_field;

   function chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel)
   {
       $this->rows = $rows;
       $this->primary_field = $primary_field;
       $this->parent_field = $parent_field;
       $this->sort_field = $sort_field;
       $this->buildChain($root_id,$maxlevel);
   }

   function buildChain($rootcatid,$maxlevel)
   {
       foreach($this->rows as $row)
       {
           $this->table[$row[$this->parent_field]][ $row[$this->primary_field]] = $row;
       }
       $this->makeBranch($rootcatid,0,$maxlevel);
   }

   function makeBranch($parent_id,$level,$maxlevel)
   {
       $rows=$this->table[$parent_id];
       foreach($rows as $key=>$value)
       {
           $rows[$key]['key'] = $this->sort_field;
       }

       usort($rows,'chainCMP');
       foreach($rows as $item)
       {
           $item['indent'] = $level;
           $this->chain_table[] = $item;
           if((isset($this->table[$item[$this->primary_field]])) && (($maxlevel>$level+1) || ($maxlevel==0)))
           {
               $this->makeBranch($item[$this->primary_field], $level+1, $maxlevel);
           }
       }
   }
}

function chainCMP($a,$b)
{
   if($a[$a['key']] == $b[$b['key']])
   {
       return 0;
   }
   return($a[$a['key']]<$b[$b['key']])?-1:1;
}



function get_compid($link,$type){
	global $database;
	$database = &JFactory::getDBO();
	$comp_id=0;
	
	$link=substr($link,(strpos($link,"?")+1));
	//echo $link;
	$opt=array();
	parse_str($link, $opt);
	$opt['task'] = @$opt['task'] ? $opt['task']: "";
	$opt['id'] = @$opt['id'] ? $opt['id']: 0;
	$opt['contact_id'] = @$opt['contact_id'] ? $opt['contact_id']: 0;
	$opt['feedid'] = @$opt['feedid'] ? $opt['feedid']: 0;
	$opt['option'] = @$opt['option'] ? $opt['option']: "";
	
	
	if($type=="component"){
		  $sql =  "SELECT  #__components.id 
                FROM #__components                                  
                WHERE #__components.parent=0
                AND #__components.link = 'option=".$opt['option']."'
                ";
        $database->setQuery( $sql );
        $comp_id = $database->loadResult();
		//echo $comp_id;
	}else if($type=="url"){
		$comp_id=0;
	
	}else{
		$comp_id=$opt['id']?$opt['id']:($opt['contact_id']?$opt['contact_id']:$opt['feedid']);
	}
	
	return $comp_id;
}


function saveMenu( $id, $option )
{
	global $database, $my, $Itemid,$mainframe;
	$database = &JFactory::getDBO();
$my = & JFactory::getUser();
$menutype=strval( JRequest::getVar( 'menutype', '' ) );
	$name=strval( JRequest::getVar( 'menuname', '' ) );
    $new=strval( JRequest::getVar( 'new', '' ) );
    $copy=strval( JRequest::getVar( 'copymenu', '' ) );
    $data2=strval( JRequest::getVar( 'php_out', '' ) );
	$menuid=intval( JRequest::getVar( 'menu_id', '' ) );
	$limit=intval( JRequest::getVar( 'limit', 0 ) );
	$limitstart=intval( JRequest::getVar( 'limitstart', 0 ) );
	$data3=explode("}}",$data2);

	
	if($new || $copy){
		
		
	 $query = "SELECT menutype"
	. "\n FROM #__menu_types"
	;
	$database->setQuery( $query );
	$menus = $database->loadResultArray();
	foreach ( $menus as $menu ) {
		//echo $name;
		if ( $menu == $name ) {
			echo "<script> alert('A menu already exists with that name - you must enter a unique Menu Name'); window.history.go(-1); </script>\n";
			exit;
		}	
	}
	$database->setQuery( "INSERT INTO #__menu_types VALUES ('','".$name."','".$name."','".$name."')");
			$database->query();
		$row 	=& JTable::getInstance('module');
		//$row = new mosModule( $database );
        // load the row from the db table
        $row->title=$name;
        $row->module="mod_mainmenu";
        $row->params="menutype=".$name;
        $row->position="left";
         if (!$row->check()) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
         }
         if (!$row->store()) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
    }
    $row->checkin();
  //  $row->updateOrder( "position='$row->position'" );
     $menutype=$name;   
    // echo "hello";   
        
    }
    	
    //	echo $menutype;
    	
    	
    $sql = "SELECT #__menu.* 
                FROM #__menu 
                WHERE #__menu.menutype = '".$menutype."' 
                AND access <= '$my->gid'
                  AND published >= '0'
                ORDER BY parent, ordering
            ";
	$database->setQuery( $sql   );
	$result = $database->loadObjectList();
	
	$swmenumaker_array=array();

	foreach ($result as $result2) {
		$order=0;
		$swmenumaker_array[] =array("ID" => $result2->id  , 
		"PARENT" => $result2->parent ,  "ORDER" => $result2->ordering );
	}
	
	// $swmenumaker_array= fixOrder2($swmenumaker_array, 0);
	if (count($swmenumaker_array)){
		$ordered = chain('ID', 'PARENT', 'ORDER', $swmenumaker_array, 0, 15);
		$i=0;
		
	}else{
		$ordered = array();
		$menudisplay=0;
	}
    $oldmenu=$swmenumaker_array;
    //print_r($oldmenu);
    	
	
	$swmenumaker_array=array();
	$counter=0;
	
	$database->setQuery( "SELECT MAX(id) FROM #__menu" );
    $database->query();
    $maxid=$database->loadResult();
    $start=$maxid;
    $maxid++;
   // echo $start."<br />".$data3;
	foreach ($data3 as $dat){
		
		$data4=explode(";;",$dat);
		//$new_parent_id=get_parent($data4[1],$data3);
		if(@$data4[3]){
			$qtype="update";
		$item_id=( $data4[12]  );
		if($item_id=="undefined"||$item_id=="0" || $item_id>$maxid){
			$qtype="insert";
			$item_id=$maxid;
			$maxid++;
			//$oldid=$data4[12];
			//echo $data4[1];
		//	$data4=make_parent($item_id,$data4[0],$data4);
		}
	//	echo $item_id;
		$new_parent_id=get_parent($data4[1],$data3);
		$linktype=$data4[11];
		$published=$data4[8];
		$access=$data4[9];
		$params=$data4[10];
		$utaccess=$data4[13];
		$compid=$data4[14];
		
		//echo "<br />".$item_id." ".$oldid." ".$new_parent_id."<br />";
		
		$row 	=& JTable::getInstance('menu');
		//$row = new mosMenu($database);
		
		$row->name=$data4[3];
		$row->browserNav=$data4[6];
		
		$row->link=$data4[4];
		
		$row->ordering=($data4[7]+1);
		$row->type=$data4[11];
		
		$row->id=$item_id;
		
		$row->parent=$new_parent_id;
		$row->published=$data4[8];
		$row->componentid=$compid;
		$row->access=$data4[9];
		$row->utaccess=$utaccess;
		$row->params=urldecode($data4[10]);
		$row->menutype=$name;
		//echo $compid;
		$swmenumaker_array[$counter] =array("TITLE" => $row->name,
		"NAME" => $row->name, "URL" =>  $row->link , "ID" => $row->id  , 
		"PARENT" => $row->parent ,  "ORDER" => $row->ordering, "LINKTYPE" => $row->type,
		"TYPE" => $row->type, "ACCESS" => $row->access, "COMPID" => $row->componentid,
		"PUBLISHED" => $row->published, "UTACCESS" => $row->utaccess,
		"TARGET" => $row->browserNav,"PARAMS" => $row->params, "QTYPE" => $qtype ,"TREEID" =>$data4[0],"TREEP" =>$data4[1] );
		}
		$counter++;
	}
	for($i=0;$i<$counter;$i++){
		if (((@$swmenumaker_array[$i]['PARENT']=="undefined")||(@$swmenumaker_array[$i]['PARENT']>$maxid))&&(@$swmenumaker_array[$i]['PARENT']!="0")){
		//	echo $swmenumaker_array[$i]['TREEP'];
			$swmenumaker_array[$i]['PARENT']=make_parent($swmenumaker_array[$i]['TREEP'],$swmenumaker_array);
		//	echo "<br />".$swmenumaker_array[$i]['ID']." ".$swmenumaker_array[$i]['PARENT']."<br />";
		}
	}
	
		
	foreach ($swmenumaker_array as $menu){
		
		$menu['TITLE']=str_replace("\\","",$menu['TITLE']);
		$menu['TITLE']=str_replace("'","\'",$menu['TITLE']);
		$alias=strtolower(str_replace(" ","-",$menu['TITLE']));
	//	$alias=str_replace("'","\'",$alias);
		if($menu['TYPE']=="separator"){$menu['TARGET']=3;}
		
		if($menu['TYPE']!="separator"&&$menu['TYPE']!="url"){$menu['TYPE']="component";}
				
		$menu['URL']=str_replace("&amp;","&",$menu['URL']);
		$menu['COMPID']=get_compid($menu['URL'],$menu['TYPE']);
		if($menu['TITLE']){	
			//echo $menu['PARAMS']."<br />";		
			if($menu['QTYPE']=="update"){
//echo $menu['TITLE'];
			$database->setQuery( "UPDATE #__menu SET  name='".$menu['TITLE']."', link='".$menu['URL']."', type='".$menu['TYPE']."', published='".$menu['PUBLISHED']."', parent='".$menu['PARENT']."', componentid='".$menu['COMPID']."', ordering='".$menu['ORDER']."', browserNav='".$menu['TARGET']."', access='".$menu['ACCESS']."', params='".urldecode($menu['PARAMS'])."' WHERE id='".$menu['ID']."'");
			$database->query();


		}elseif($menu['QTYPE']=="insert"){
//echo $menu['ID']." ".$menutype." ".$menu['TITLE']." ".$alias." ".$menu['URL']." ".$menu['TYPE']." ".$menu['PUBLISHED']." ".$menu['PARENT']." ".$menu['COMPID']."','0','".$menu['ORDER']."','0','0','0','".$menu['TARGET']."','".$menu['ACCESS']."','0','','0','0','0'<br />";
			$database->setQuery( "INSERT INTO #__menu VALUES ('".$menu['ID']."','".$menutype."','".$menu['TITLE']."','".$alias."','".$menu['URL']."','".$menu['TYPE']."','".$menu['PUBLISHED']."','".$menu['PARENT']."','".$menu['COMPID']."','0','".$menu['ORDER']."','0','0','0','".$menu['TARGET']."','".$menu['ACCESS']."','0','".$menu['PARAMS']."','0','0','0')");
			$database->query();

		}
		}
		
			
	}
	
	foreach($swmenumaker_array as $new){
		$new2[]=$new['ID'];
}
	foreach($oldmenu as $old){
		if (!in_array($old['ID'], $new2)) {
  
$database->setQuery( "DELETE FROM #__menu WHERE id='".$old['ID']."'" );
            $database->query();
}
	}		
	 $limit = intval( JRequest::getVar( 'limit', 10 ) );
    $limitstart = intval( JRequest::getVar( 'limitstart', 0 ) );
   $msg="Menu sucessfully saved";
$mainframe->redirect( "index2.php?option=$option&task=showmenus&Itemid=$Itemid&limit=$limit&limitstart=$limitstart",$msg );
	HTML_swmenumaker::footer( );
}



function get_parent($id,$tree){
$parent=0;
$temp_id=explode("-", $id);
$pid=@$temp_id[1];		
foreach ($tree as $dat){
		$data4=explode(";;",$dat);
		$temp_id=explode("-", $data4[0]);
		$newid=@$temp_id[1];
		if(($pid==$newid)&&$pid){	
	      $parent=$data4[12];
		}	
}
return $parent;
}

function make_parent($pid,$tree){
$parent=0;
$temp_id=explode("-", $pid);
$pid=@$temp_id[1];	
//echo $pid;	
$count=0;
foreach ($tree as $dat){
	$temp_id=explode("-", $dat['TREEID']);
		$newid=@$temp_id[1];
		if($pid==$newid){
			$parent=$dat['ID'];
			//echo $id;
		}
		$count++;
}
//echo $parent;
return $parent;
}





?>
